//
//  ChatRoomViewController.m
//  YMRTC
//
//  Created by admin on 2022/4/19.
//

#import "ChatRoomViewController.h"
#import <Masonry/Masonry.h>
#import "UIView+Helper.h"
#import "ContactViewController.h"
#import "UIViewController+HUD.h"
#import "RZSlideMenuView.h"
#import "CreateGroupViewController.h"
#import "RoomInfoViewController.h"
#import "ChatConversationViewController.h"
#import "ChatEmptyView.h"
@interface ChatRoomViewController ()<UISearchBarDelegate>
@property (nonatomic, strong) UIButton *moreBtn;
@property (nonatomic,strong)NSMutableArray *userArray;
@property (nonatomic, strong) RZSlideMenuView *menuView;
@property (nonatomic,strong)ChatEmptyView *emptyView;
@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)UIView *headerView;
@end

@implementation ChatRoomViewController

- (id)init {
    self = [super init];
    if (self) {
        //设置要显示的会话类型
        self.displayConversationTypeArray = @[@(ConversationType_CHATROOM)];
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.moreBtn];
    self.navigationItem.rightBarButtonItem = right;
    [self setEmptyView];
    [self initSearchBar];

  
  
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

-(void)initSearchBar{
  
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.showsCancelButton = NO;
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    _searchBar.delegate = self;
    _searchBar.tintColor = [UIColor whiteColor];
    _searchBar.placeholder = @"搜索聊天室";
    [_searchBar setBackgroundImage:[UIImage new]];
    if (@available(iOS 13.0, *)) {
        
        UITextField * textField = self.searchBar.searchTextField;
        textField.backgroundColor =  [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        textField.layer.cornerRadius = 15;
        textField.clipsToBounds = YES;
        UIColor *color = [UIColor grayColor];
        [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索聊天室" attributes:@{NSForegroundColorAttributeName:color}]];
    }else{
        
        UITextField * textField = [self.searchBar valueForKey:@"searchField"];
        textField.backgroundColor =  [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        textField.layer.cornerRadius = 15;
        textField.clipsToBounds = YES;
        UIColor *color = [UIColor grayColor];
        [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索聊天室" attributes:@{NSForegroundColorAttributeName:color}]];
        
    }

    self.conversationListTableView.tableHeaderView = self.headerView;
    self.conversationListTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

    
    [self.headerView addSubview:_searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.mas_equalTo(self.headerView.mas_centerY);
        make.left.mas_equalTo(self.headerView.mas_left).offset(10);
        make.right.mas_equalTo(self.headerView.mas_right).offset(-10);
        make.height.mas_equalTo(50);
        
    }];
    

    
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [self.view endEditing:YES];
  
    //获取数据
    [[YMIMClient sharedClient].roomManager searchRoomListWithCount:0 label:0 roomName:searchBar.text completionBlock:^(NSArray<YMConversation *> * _Nonnull dataSource, YMErrorCode code) {
        
        if (code != YM_SUCCESS) {
             return;
        }
        [self.dataArray removeAllObjects];
        for (int i = 0 ; i<dataSource.count; i++) {

            YMConversation *conversation = [[YMConversation alloc]init];
            YMGroupInfo *info = [[YMGroupInfo alloc]init];
            info.groupId = [[dataSource[i]valueForKey:@"chatRoom"]valueForKey:@"gid"];
            info.groupAvatar = [[dataSource[i]valueForKey:@"chatRoom"]valueForKey:@"groupAvatar"];
            info.groupName = [[dataSource[i]valueForKey:@"chatRoom"]valueForKey:@"groupName"];
            info.groupType = [[[dataSource[i]valueForKey:@"chatRoom"]valueForKey:@"groupType"]intValue];
            conversation.groupInfo = info;
            [self.dataArray addObject:conversation];
            [self.conversationListTableView reloadData];
            
        }
        
    }];

    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    
    if ([searchText isEqualToString:@""]) {
        
        [self refreshConversationTableViewIfNeeded];
        NSLog(@"%@===",searchText);
    }
    
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)startShowHUD {
    [self showLoading];
    
}

- (void)endHideHUD {
    [self hideHud];
}

-(void)setEmptyView{
    
    [self.view addSubview:self.emptyView];
    [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        
    }];
 
    self.emptyConversationView = self.emptyView;
}

#pragma mark Private method
- (void)openMenu:(id)sender  {
    RZSlideMenuConfig *config = [[RZSlideMenuConfig alloc] init];
    config.direction = DirectionFromRight;
    self.menuView = [[RZSlideMenuView alloc] initWithConfig:config];
    
//    RZSlideMenuModel *chat = [RZSlideMenuModel createWithIcon:@"Menu_Chat" name:@"发起会话"];
//    RZSlideMenuModel *addfriend = [RZSlideMenuModel createWithIcon:@"Menu_Add" name:@"添加好友"];
    RZSlideMenuModel *chatRoom = [RZSlideMenuModel createWithIcon:@"Menu_GroupChat" name:@"新建聊天室"];
//    self.menuView.menuArray = @[chat,addfriend,groupchat];
    
    self.menuView.menuArray = @[chatRoom];
    [self.menuView showWithAnimation:YES];
    __weak __typeof(self) weakSelf = self;
    
    self.menuView.selectMenuAtIndex = ^(NSInteger index, RZSlideMenuModel * _Nonnull model) {
//        @strongify(self);
        [weakSelf handlerSlideMenuAtIndex:index];
    };
}


/**
 处理侧滑菜单
 */
- (void)handlerSlideMenuAtIndex:(NSInteger)index {
//    if (index == 0) {
//
//        ContactViewController *vc = [[ContactViewController alloc] init];
//        vc.hidesBottomBarWhenPushed = YES;
//        vc.showSelect = YES;
//        vc.showSingleSelect = YES;
//        vc.title = @"发起会话";
//        vc.didSelectResultBlock = ^(NSArray * _Nonnull userArray) {
//            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//            CreateGroupViewController *vc = [main instantiateViewControllerWithIdentifier:@"CreateGroupViewController"];
//            vc.hidesBottomBarWhenPushed = YES;
//            vc.uidsList = userArray;
//
//            [self.navigationController pushViewController:vc animated:YES];
//        };
//        [self.navigationController pushViewController:vc animated:YES];
//    }else if (index == 1){
//
//        AddFriendViewController *vc = [[AddFriendViewController alloc]init];
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//
//    }else if (index==2){
//
        ContactViewController *vc = [[ContactViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.showSelect = YES;
        vc.title = @"新建聊天室";
        vc.didSelectResultBlock = ^(NSArray * _Nonnull userArray) {
            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            CreateGroupViewController *vc = [main instantiateViewControllerWithIdentifier:@"CreateGroupViewController"];
            vc.hidesBottomBarWhenPushed = YES;
            vc.uidsList = userArray;
            vc.title = @"新建聊天室";
            vc.creteType = RoomType;
            [self.navigationController pushViewController:vc animated:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
//    }
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 table cell was clicked
 */
- (void)onSelectedTableRow:(UITableView *)tableView conversationModel:(YMConversation *)model atIndexPath:(NSIndexPath *)indexPath {
 
    ChatConversationViewController *vc = [[ChatConversationViewController alloc] initWithConversationType:model.groupInfo.groupType targetId:model.targetId];
    vc.hidesBottomBarWhenPushed = YES;
    vc.title = model.groupInfo.groupType == 0 ? model.userList.firstObject.userName : model.groupInfo.groupName;
    [self.navigationController pushViewController:vc animated:YES];
  
}

- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:[UIImage imageNamed:@"Message_Plus"] forState:UIControlStateNormal];
        _moreBtn.frame = CGRectMake(0, 0, 40, 40);
        [_moreBtn addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}

-(ChatEmptyView *)emptyView{
   
    if (_emptyView == nil) {
        
        _emptyView = [[ChatEmptyView alloc]init];
     
    }
    
    return _emptyView;
    
}
-(UIView *)headerView{
    
    if (_headerView == nil) {
        
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    
    return _headerView;
}
@end
